package leetcodecompetition.S102;

import CommonStructure.TreeNode;

import java.util.*;

public class T6335 {
    List<Integer> list;

    public TreeNode replaceValueInTree(TreeNode root) {
        list=new ArrayList<>();
        Queue<TreeNode> stack = new LinkedList<>();
        stack.offer(root);
        while (!stack.isEmpty()) {
            int sum = 0;
            int len = stack.size();
            for (int i = 0; i < len; i++) {
                TreeNode t = stack.poll();
                System.out.print(t.val);
                sum += t.val;
                if (t.left != null) {
                    stack.offer(t.left);
                }
                if (t.right != null) {
                    stack.offer(t.right);
                }
            }
            list.add(sum);
        }
        dp(root, 0, 0);
        return root;
    }


    public void dp(TreeNode father, int plies, int brotherVal) {
        System.out.println(list.get(plies)+"  "+brotherVal+"  "+father.val);
        father.val = list.get(plies) - brotherVal-father.val;
        if (father.left == null && father.right == null) return;
        if (father.left != null && father.right != null) {
            int leftVal=father.left.val;
            dp(father.left, plies + 1, father.right.val);
            dp(father.right, plies + 1, leftVal);
        }
        if (father.left == null) {
            dp(father.right, plies + 1, 0);
        }
        if (father.right == null) {
            dp(father.left, plies + 1, 0);
        }
    }
}

